<template>
  <div class="page flex flex-col gap-y-3 p-3 h-dvh">
    <n-card :bordered="false">
      <n-form label-align="left" label-placement="left" label-width="auto" ref="formRef" :inline="true" :model="formParams" :show-feedback="false">
        <n-grid responsive="screen" cols="1 s:1 m:2 l:3 xl:4 2xl:4" :collapsed="isCollapse" :x-gap="16" :y-gap="16">
          <n-form-item-gi label="关键词"> <n-input v-model:value="formParams.keyword" placeholder="请输入关键词" /> </n-form-item-gi>
          <n-gi :suffix="true">
            <n-space align="center" justify="end">
              <n-button v-if="hasPermission('bmpch:menu:list', '查询菜单管理列表')" type="primary" :loading="searchBtnLoading" @click="handleSearch">
                <template #icon>
                  <n-icon>
                    <SearchOutlined />
                  </n-icon>
                </template>
                查询
              </n-button>
              <n-button @click="() => (formParams = new FormParams())">重置</n-button>
              <n-button type="primary" icon-placement="right" text @click="() => (isCollapse = !isCollapse)">
                <template #icon>
                  <n-icon size="14" v-if="isCollapse">
                    <DownOutlined />
                  </n-icon>
                  <n-icon size="14" v-else>
                    <UpOutlined />
                  </n-icon>
                </template>
                {{ isCollapse ? '展开' : '收起' }}
              </n-button>
            </n-space>
          </n-gi>
        </n-grid>
      </n-form>
    </n-card>
    <n-card :bordered="false" class="flex-1">
      <DataTable
        remote
        striped
        :row-key="(row: BMPCH.MenuQry001Output_MenuDto) => row.menuId"
        :columns="tableColumns"
        :data="dataList"
        :loading="dataLoading"
        :scroll-x="1200"
        @reload="loadData"
      >
        <template #title>
          <n-space align="center">
            <n-button v-if="hasPermission('bmpch:menu:add', '新建菜单')" type="primary" @click="() => handleAdd()">
              <template #icon>
                <n-icon>
                  <PlusOutlined />
                </n-icon>
              </template>
              新建
            </n-button>
          </n-space>
        </template>
      </DataTable>
      <Edit v-model:show="showModal" :biz-id="bizId" :menu-pid="menuPid" @refresh="loadData" />
      <RouteTree v-model:show="showRouteTreeModal" :menu-id="bizId" @refresh="loadData" />
    </n-card>
  </div>
</template>

<script lang="ts" setup>
import { h, ref, onMounted } from 'vue';
import { NSpace, NIcon, NButton, NPopconfirm, NInput, NInputNumber } from 'naive-ui';
import type { DataTableColumns, FormInst } from 'naive-ui';
import { removeEmptyField } from '@yanfan/common/utils';
import DataTable from '@/components/DataTable';
import { menuOrdrNumUpd, menuQry001, menuRmv } from '@yanfan/bmpch-tsapi/menu';
import type * as BMPCH from '@yanfan/bmpch-tsapi/types';
import {
  DownOutlined,
  UpOutlined,
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  TableOutlined,
  SortAscendingOutlined,
} from '@vicons/antd';
import { usePermission } from '@yanfan/common/hooks';
import Edit from './Edit.vue';
import RouteTree from './RouteTree.vue';

defineOptions({
  name: 'BmpchMenuList',
  titl: '菜单管理列表',
});

const { hasPermission } = usePermission();

class FormParams {
  keyword: string | null = null;
}

const tableColumns: DataTableColumns<BMPCH.MenuQry001Output_MenuDto> = [
  { title: '菜单名称', key: 'menuNm', width: 180 },
  { title: '图标', key: 'icon', width: 100 },
  { title: '路径', key: 'path', width: 200 },
  {
    title: '排序',
    key: 'ordrNum',
    width: 80,
    align: 'right',
    render(row) {
      return h(
        NPopconfirm,
        {
          onUpdateShow: (show) => {
            if (show) {
              ordrNum.value = row.ordrNum;
            }
          },
          onPositiveClick: () => {
            if (ordrNum.value === null) {
              window.$message.warning('排序号不能为空');
              return;
            }
            menuOrdrNumUpd({ menuId: row.menuId, ordrNum: ordrNum.value }).then(() => {
              loadData();
            });
          },
        },
        {
          icon: () => h(NIcon, { size: 18 }, () => h(SortAscendingOutlined)),
          default: () => h(NInputNumber, { value: ordrNum.value, onUpdateValue: (value) => (ordrNum.value = value) }),
          trigger: () =>
            h(
              NButton,
              { text: true, iconPlacement: 'right' },
              { icon: () => h(NIcon, { size: 18 }, () => h(EditOutlined)), default: () => row.ordrNum },
            ),
        },
      );
    },
  },
  { title: '备注', key: 'rmrk' },
  {
    title: '操作',
    key: 'actions',
    width: 270,
    align: 'center',
    fixed: 'right',
    render(row) {
      return h(NSpace, { align: 'center', justify: 'center' }, () => [
        h(
          NButton,
          { type: 'info', text: true, onClick: () => handleRouteLink(row) },
          { icon: () => h(NIcon, { size: 18 }, () => h(TableOutlined)), default: () => '路由' },
        ),
        h(
          NButton,
          { type: 'info', text: true, onClick: () => handleAdd(row) },
          { icon: () => h(NIcon, { size: 18 }, () => h(PlusOutlined)), default: () => '添加' },
        ),
        h(
          NButton,
          { type: 'info', text: true, onClick: () => handleEdit(row) },
          { icon: () => h(NIcon, { size: 18 }, () => h(EditOutlined)), default: () => '编辑' },
        ),
        h(
          NPopconfirm,
          { onPositiveClick: () => handleDelete(row) },
          {
            trigger: () =>
              h(NButton, { type: 'error', text: true }, { icon: () => h(NIcon, { size: 18 }, () => h(DeleteOutlined)), default: () => '删除' }),
            default: () => '确定要删除该数据吗？',
          },
        ),
      ]);
    },
  },
];

const showModal = ref(false);
const showRouteTreeModal = ref(false);
const isCollapse = ref(false);
const formRef = ref<FormInst | null>(null);
const formParams = ref(new FormParams());
const searchBtnLoading = ref(false);
const bizId = ref<string | null>(null);
const menuPid = ref<string | null>(null);
const ordrNum = ref<number | null>(0);
const dataLoading = ref(false);
const dataList = ref<BMPCH.MenuQry001Output_MenuDto[]>([]);

onMounted(() => {
  loadData();
});

function loadData() {
  dataLoading.value = true;
  menuQry001({ ...removeEmptyField(formParams.value) })
    .then((data) => {
      dataList.value = data.list;
    })
    .finally(() => {
      dataLoading.value = false;
      searchBtnLoading.value = false;
    });
}

function handleSearch() {
  searchBtnLoading.value = true;
  loadData();
}

function handleAdd(row?: BMPCH.MenuQry001Output_MenuDto) {
  if (row) {
    menuPid.value = row.menuId;
  } else {
    menuPid.value = 'ROOT';
  }
  bizId.value = String();
  showModal.value = true;
}

function handleEdit(row: BMPCH.MenuQry001Output_MenuDto) {
  bizId.value = row.menuId;
  showModal.value = true;
}

function handleDelete(row: BMPCH.MenuQry001Output_MenuDto) {
  menuRmv({ menuId: row.menuId }).then(() => {
    window.$message.success('删除成功');
    loadData();
  });
}

function handleRouteLink(row: BMPCH.MenuQry001Output_MenuDto) {
  bizId.value = row.menuId;
  showRouteTreeModal.value = true;
}
</script>

<style lang="scss" scoped></style>
